import pymysql
from dbutils.pooled_db import PooledDB
import threading

# 线程
from threading import Thread


"""
storage = {
    111:{'stack':[(conn, cursor),]},
    222:{'stack':[(conn, cursor),]},
}
"""

# 创建数据库连接池
POOL = PooledDB(
    creator=pymysql,  # 使用链接数据库的模块
    maxconnections=6,  # 连接池允许的最大连接数，0和None表示不限制连接数
    mincached=2,  # 初始化时，链接池中至少创建的空闲的链接，0表示不创建
    blocking=True,  # 连接池中如果没有可用连接后，是否阻塞等待。True，等待；False，不等待然后报错
    # ping MySQL服务端，检查是否服务可用。# 如：0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always
    ping=0,
    host="localhost",
    port=3306,
    user="root",
    password="123456",
    database="flasktest",
    charset="utf8",
)


class SqlHelper(object):
    # 初始化
    def __init__(self) -> None:
        self.conn = None
        self.cursor = None

    # 获取连接、游标
    def open(self):
        # 去连接池中获取一个连接
        conn = POOL.connection()

        cursor = conn.cursor()

        return conn, cursor

    # 关闭
    def close(self, conn, cursor):
        # 将连接放回到连接池
        cursor.close()
        conn.close()

    # with enter
    def __enter__(self):
        self.conn, self.cursor = self.open()

        return self.cursor

    # with exit
    def __exit__(self, exc_type, exc_val, excc_tb):
        self.cursor.close()
        self.conn.close()


#####################

"""
需要自己创建对象
db = SqlHelper()
with db as cursor:
    cursor.execute('select * from user')

或者

with SqlHelper() as cursor:
    cursor.execute('select * from user')
"""
